import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getCookie, getToken, setToken } from '@/utils/auth'
import router from '@/router'
import Vue from 'vue'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_PREFIX, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 * 60 // request timeout
})

// 设置请求次数，请求的间隙
service.defaults.retry = 5
service.defaults.retryDelay = 1000

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.url && config.url.indexOf('/new/notice') < 0) {
      config['cancelToken'] = new axios.CancelToken(c => {
        Vue.$httpRequestList.push(c)
      })
    }
    // do something before request is sent
    if (!config['notAuth'] && store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    config.headers['X-Requested-Cookie'] = getCookie()
    if (config['prefix'] === false) {
      config.baseURL = process.env.VUE_APP_BASE_URL
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // Refresh token
    if (response.headers.authorization) {
      setToken(response.headers.authorization, getCookie())
    }

    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== undefined && res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      store.commit('app/SET_LOADING', false)
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 403) {
        // MessageBox.confirm(res.message, 'Authorize', {
        //   confirmButtonText: '重新登录',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
        store.dispatch('user/resetToken').then(() => {
          router.push(`/login`)
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (error.response) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      store.commit('app/SET_LOADING', false)
      return Promise.reject(error)
    } else {
      // 处理超时的情况
      const config = error.config
      // If config does not exist or the retry option is not set, reject
      if (!config || !config.retry) return Promise.reject(error)

      // Set the variable for keeping track of the retry count
      config.__retryCount = config.__retryCount || 0

      // Check if we've maxed out the total number of retries
      if (config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(error)
      }

      // Increase the retry count
      config.__retryCount += 1

      // Create new promise to handle exponential backoff
      const backoff = new Promise(function(resolve) {
        setTimeout(function() {
          resolve()
        }, config.retryDelay || 1)
      })

      // Return the promise in which recalls axios to retry the request
      return backoff.then(function() {
        return axios(config)
      })
    }
  }
)

/**
 * 并发请求
 * @param request
 * @param callback
 */
export const all = (request, callback) => {
  axios.all(request).then(axios.spread(function(...response) {
    const res = []
    const length = response.length
    for (let i = 0; i < length; i++) {
      const result = handleResponse(response[i])
      if (!result) {
        callback(false)
        return
      }
      res.push(result)
    }
    callback(res)
  })).catch(e => {
    if (e.message !== 'interrupt') {
      callback(false)
    }
  })
}

/**
 * 处理并发响应数据
 * @param response
 * @returns {*|boolean}
 */
function handleResponse(response) {
  if (response.code === 200) {
    if (response['current_page']) {
      return response
    } else {
      return response.data ? response.data : true
    }
  } else if (response.code === 403) {
    store.dispatch('user/resetToken').then(() => {
      router.push({ path: '/login' })
    })
    return false
  } else {
    Message({
      message: response.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
    return false
  }
}

export default service
